import JSZip from 'jszip'
import FileSaver from 'file-saver'

// 通过url 将文件打包下载成zip并指定文件名
export const downloadZip = async (urls, name) => {
  const zip = new JSZip();
  // 使用 Promise.all 等待所有图片下载完成
  await Promise.all(
    urls.map(async (url) => {
      try {
        // 获取图片内容
        const response = await fetch(url.url);
        const blob = await response.blob();
        // 将图片内容添加到zip中
        zip.folder(name || "attachment").file(url.name, blob, {binary: true});
      } catch (error) {
        console.error(`下载文件失败: ${url.url}`, error);
      }
    })
  );
  const content = await zip.generateAsync({ type: "blob" });
  FileSaver.saveAs(content, name + ".zip" || "download.zip");
};


// 通过url下载一个xlsx文件
export const downloadXlsx = async (url, name) => {
  const response = await fetch(url);
  const blob = await response.blob();
  FileSaver.saveAs(blob, name + ".xlsx" || "download.xlsx");
};
